package xcmg.device.service.sale;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.sale.SaleIntentionDetailDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnApplyDO;
import xcmg.device.dao.entity.salesReturn.SalesReturnApplyDetailDO;
import xcmg.device.dao.mapper.MaterialLocationRelationMapper;
import xcmg.device.dao.mapper.SaleIntentionDetailMapper;
import xcmg.device.dao.mapper.salesReturn.ReturnApplyDetailMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.service.marketing.MarketingActivityService;
import xcmg.device.service.vo.basic.MaterialLocationRelationVO;
import xcmg.device.service.vo.marketing.MarketingActivityPriceVO;
import xcmg.device.service.vo.salesReturn.SalesReturnApplyDetailVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.StringUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by LiChangjiang on 2018/3/6 0006.
 */
@Service
public class ReturnApplyDetailService
{
    @Autowired
    private ReturnApplyDetailMapper returnApplyDetailMapper;

    @Autowired
    private SaleIntentionDetailMapper saleIntentionDetailMapper;

    @Autowired
    private FastGenClient fastGenClient;

    @Autowired
    private MarketingActivityService marketingActivityService;

    @Autowired
    private MaterialLocationRelationMapper materialLocationRelationMapper;

    /**
     * 根据退货申请ID查询零件详细
     *(返回多个)
     * @param applyId String
     * @return List<SalesReturnApplyDetailDO>
     *  addby huhuawei/2018-9-14
     */
    public List<SalesReturnApplyDetailVO> itemsById(String applyId)
    {
        List<SalesReturnApplyDetailVO> detailVOS=new ArrayList<>();
        List<SalesReturnApplyDetailDO> salesReturnApplyDetailDOs = returnApplyDetailMapper.list(applyId);
        for(SalesReturnApplyDetailDO detail:salesReturnApplyDetailDOs){
            detailVOS.add(getVO(detail));
        }
        return detailVOS;
    }

    /**
     * 查询退货申请中的零件信息列表
     *
     * @param applyId String
     * @return List
     * @throws Exception 
     */
    public List<SalesReturnApplyDetailVO> list(String applyId, SalesReturnApplyDO returnApplyDO) throws Exception
    {
        List<SalesReturnApplyDetailDO> salesReturnApplyDetailDOs = returnApplyDetailMapper.list(applyId);

        List<SalesReturnApplyDetailVO> resultList = new ArrayList<>();

        if (ListUtil.isNullOrEmpty(salesReturnApplyDetailDOs))
        {
            return resultList;
        }

        MaterialLocationRelationVO materialLocationRelationVO = new MaterialLocationRelationVO();
        for (SalesReturnApplyDetailDO record : salesReturnApplyDetailDOs)
        {
            SalesReturnApplyDetailVO applyDetailVO =     getVO(record);
            if(!StringUtil.isNullOrEmpty(returnApplyDO.getSaleNo())){
                SaleIntentionDetailDO saleIntentionDetailDO =   saleIntentionDetailMapper.selectByNo(record.getSaleNo(),record.getMaterialsNo());
                if(saleIntentionDetailDO==null){
                    continue;
                }
                applyDetailVO.setReturnApplyAmount(saleIntentionDetailDO.getReturnApplyAmount());
            }else{
                applyDetailVO.setMarketingActivityPriceVOList(marketingActivityService.activityPriceList(returnApplyDO.getPurchaseOrgId(),returnApplyDO.getSupplierOrgId(),record.getMaterialsNo()));
            }
            materialLocationRelationVO.setMaterialNo(record.getMaterialsNo());
            materialLocationRelationVO.setOrgId(returnApplyDO.getSupplierOrgId());
            applyDetailVO.setStockLocationList(materialLocationRelationMapper.list(materialLocationRelationVO));
            resultList.add(applyDetailVO);
        }

        return resultList;
    }

    /**
     * 修改销售单零件详细的状态，退货申请，判断销售单零件是否全部退货，更改退货申请数量以及状态
     * @param applyDetailDO SalesReturnApplyDetailDO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    private ErrorCode updateSaleIntentionDetail(SalesReturnApplyDetailDO applyDetailDO) throws  Exception
    {
        Integer returnFlag = 0;//退回申请标记（0未退货申请，1部分退货申请，2全部退货申请）
        SaleIntentionDetailDO saleIntentionDetailDO = saleIntentionDetailMapper.selectByNo(applyDetailDO.getSaleNo(), applyDetailDO.getMaterialsNo());
        if(saleIntentionDetailDO==null){
            return ErrorCode.Failure;
        }
        if(saleIntentionDetailDO.getReturnApplyAmount()==null){
            saleIntentionDetailDO.setReturnApplyAmount(new BigDecimal("0"));
        }
        //判断销售单中调整后数量与（已经退货+本次申请退货数量）进行比较
        if (saleIntentionDetailDO.getAmountAfterAdjust().compareTo(saleIntentionDetailDO.getReturnApplyAmount().add(applyDetailDO.getApplyQty())) > 0)
        {
            returnFlag = 1;
        }
        else if (saleIntentionDetailDO.getAmountAfterAdjust().compareTo(saleIntentionDetailDO.getReturnApplyAmount().add(applyDetailDO.getApplyQty())) == 0)
        {
            returnFlag = 2;
        }
        else
        {
            throw new Exception("退货数量不能大于销售数量！");
        }

        int ret = saleIntentionDetailMapper.updateByReturnApply(applyDetailDO.getApplyQty(), applyDetailDO.getSaleNo(), applyDetailDO.getMaterialsNo(), returnFlag);
        if (ret == 0)
        {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }



    /**
     * 添加退货申请详情（零件信息）
     *
     * @param salesReturnApplyDetailDOList List<SalesReturnApplyDetailDO>
     * @return ErrorCode
     * @throws Exception Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode insert(List<SalesReturnApplyDetailDO> salesReturnApplyDetailDOList) throws Exception
    {
        for (SalesReturnApplyDetailDO detailDO : salesReturnApplyDetailDOList)
        {
            ErrorCode errorCode = insertItem(detailDO);
            if (ErrorCode.Success != errorCode)
            {
                throw new Exception("添加退货申请零件信息异常！");
            }
            ErrorCode updateRet = updateSaleIntentionDetail(detailDO);
            if (updateRet != ErrorCode.Success)
            {
                throw new Exception("更改销售单零件状态异常！");
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 添加退货申请详情单条记录（零件信息）
     *
     * @param applyDetailDOList SalesReturnApplyDetailDO
     * @return ErrorCode ErrorCode
     * @throws Exception Exception
     */
    public ErrorCode insertItem(SalesReturnApplyDetailDO applyDetailDOList) throws Exception
    {
        ActionResult<String> textResult = fastGenClient.textGuid();
        if (textResult == null || textResult.getCode() != 0)
        {
            return ErrorCode.Failure;
        }
        applyDetailDOList.setId(textResult.getValue());
        int addRet = returnApplyDetailMapper.insert(applyDetailDOList);

        if (0 >= addRet)
        {
            throw new Exception("添加退货申请步骤，添加零件信息异常！");
        }
        return ErrorCode.Success;
    }

    /**
     * 查询零件详细
     *
     * @param id String
     * @return SalesReturnApplyDetailVO
     */
    public SalesReturnApplyDetailVO itemById(String id)
    {
        SalesReturnApplyDetailDO salesReturnInDetailDO = returnApplyDetailMapper.itemById(id);
        return getVO(salesReturnInDetailDO);
    }

    /**
     * 更新退货申请零件信息
     * @param applyDetailVO SalesReturnApplyDetailVO
     * @return ErrorCode
     */
    public ErrorCode update(SalesReturnApplyDetailVO applyDetailVO)
    {
        returnApplyDetailMapper.update(getDO(applyDetailVO));
        return ErrorCode.Success;
    }


    /**
     * 删除退货申请零件信息
     *
     * @param applyId String
     * @return ErrorCode
     */
    public ErrorCode deleteByApplyId(String applyId)
    {
        returnApplyDetailMapper.deleteByApply(applyId);
        return ErrorCode.Success;
    }


    /**
     * @param beanDO SalesReturnApplyDetailDO
     * @return SalesReturnApplyDetailVO
     */
    private SalesReturnApplyDetailVO getVO(SalesReturnApplyDetailDO beanDO)
    {
        if (null == beanDO)
        {
            return null;
        }
        SalesReturnApplyDetailVO beanVO = new SalesReturnApplyDetailVO();

        BeanUtils.copyProperties(beanDO, beanVO);

        if(1==beanDO.getIsReturn())
        {
            beanVO.setIsReturnDesc("退货中");
        }else  if(2==beanDO.getIsReturn())
        {
            beanVO.setIsReturnDesc("退货完成");
        }else
        {
            beanVO.setIsReturnDesc("未退货");
        }

        if(1==beanDO.getIsIn())
        {
            beanVO.setIsInDesc("入库中");
        }else  if(2==beanDO.getIsIn())
        {
            beanVO.setIsInDesc("入库完成");
        }else
        {
            beanVO.setIsInDesc("未入库");
        }
        return beanVO;
    }

    /**
     * @param beanVO SalesReturnApplyDetailVO
     * @return SalesReturnApplyDetailDO
     */
    private SalesReturnApplyDetailDO getDO(SalesReturnApplyDetailVO beanVO)
    {
        if (null == beanVO)
        {
            return null;
        }
        SalesReturnApplyDetailDO beanDO = new SalesReturnApplyDetailDO();

        beanDO.setId(beanVO.getId());
        beanDO.setApplyId(beanVO.getApplyId());
        beanDO.setMaterialsNo(beanVO.getMaterialsNo());
        beanDO.setMaterialsType(beanVO.getMaterialsType());
        beanDO.setMaterialsDes(beanVO.getMaterialsDes());
        beanDO.setUnit(beanVO.getUnit());
        if(beanVO.getApplyQty() != null){
            beanDO.setApplyQty(beanVO.getApplyQty());
        }
        beanDO.setSaleNo(beanVO.getSaleNo());
        beanDO.setDeliveryNo(beanVO.getDeliveryNo());
        beanDO.setDeliveryDetailId(beanVO.getDeliveryDetailId());
        beanDO.setReturnQty(beanVO.getReturnQty());
        beanDO.setIsReturn(beanVO.getIsReturn());
        beanDO.setIsIn(beanVO.getIsIn());
        beanDO.setQty(beanVO.getQty());
        return beanDO;
    }

}
